package com.hnas.ecard.web;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.codehaus.jackson.map.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartRequest;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.hnas.api.dto.DTOResult;
import com.hnas.api.server.PostConnServer;
import com.hnas.api.util.CommonUtil;
import com.hnas.api.util.HttpRequest;
import com.hnas.common.web.BaseAjaxResponse;
import com.hnas.common.web.WebUtil;
import com.hnas.core.dto.DTOPagedList;
import com.hnas.core.dto.DataBean;
import com.hnas.core.util.DateUtil;
import com.hnas.core.util.ExcelReader;
import com.hnas.core.util.MathUtil;
import com.hnas.core.util.StringUtil;
import com.hnas.ecard.intf.GetWXSignFromServer;
import com.hnas.ecard.orm.ECardChannelInfo;
import com.hnas.ecard.service.CheckSendRecordTaskService;
import com.hnas.ecard.service.ECardChannelInfoService;
import com.hnas.ecard.service.dto.DTOECardChannelInfo;
import com.hnas.ecard.service.search.DTOECardChannelInfoSearch;
import com.hnas.ecard.util.ChannelCodeUtil;
import com.hnas.ecard.util.QRCodeUtil;

import jxl.CellView;
import jxl.Workbook;
import jxl.format.Border;
import jxl.format.BorderLineStyle;
import jxl.format.Colour;
import jxl.write.Label;
import jxl.write.WritableCellFormat;
import jxl.write.WritableFont;
import jxl.write.WritableWorkbook;

@Controller
@RequestMapping("/backend/ecard/channel")
public class ECardChannelController {

	private ObjectMapper objectMapper = new ObjectMapper();
	private Logger logger = LoggerFactory.getLogger(ECardChannelController.class);

	@Value("#{component.wechat_appid}")
	private String wechatAppId;
	
	@Autowired
	private ECardChannelInfoService eCardChannelInfoService;
	@Autowired
	private PostConnServer postConnServer;
	@Autowired
	private CheckSendRecordTaskService checkSendRecordTaskService;
	
	@RequestMapping("/search")
	public String search(ModelMap modelMap, HttpServletRequest request, HttpServletResponse response,
			@ModelAttribute("criteria") DTOECardChannelInfoSearch criteria) {
		criteria.setTotalCount(-1);
		DTOPagedList<DTOECardChannelInfo> pg = this.eCardChannelInfoService.page(criteria);
		modelMap.put("pg", pg);
		modelMap.put("dto", criteria);

		List<DataBean> beans = new ArrayList<DataBean>();
		beans.add(new DataBean("id", "id", "渠道id", false, 150, 0));
		beans.get(beans.size() - 1).setHidden(true);
		beans.add(new DataBean("channelCode", "channelCode", "渠道编号", false, 150, 0));
		beans.get(beans.size() - 1).setHidden(true);
		beans.add(new DataBean("channelName", "channelName", "渠道名称", false, 150, 0));
		beans.add(new DataBean("qrcodeStr", "qrcodeStr", "渠道二维码", false, 150, 0));
		beans.get(beans.size() - 1).setHidden(true);
		beans.add(new DataBean("createTime", "createTime", "创建时间", false, 150, 0));
		beans.get(beans.size() - 1).setHidden(true);
		beans.add(new DataBean("updateTime", "updateTime", "修改时间", false, 150, 0));
		beans.get(beans.size() - 1).setHidden(true);
		beans.add(new DataBean("remark", "remark", "备注", true, 150, 0));
		beans.add(new DataBean("isDeleted", "isDeleted", "是否删除", false, 150, 0));
		beans.get(beans.size() - 1).setHidden(true);
		beans.get(beans.size() - 1).setDisplay(false);
		modelMap.put("beans", beans);
		modelMap.put("pageTitle", "电子卡渠道信息");
		return "/backend/ecard/list_ecard_channel";
	}

	@RequestMapping("/add")
	@ResponseBody
	public BaseAjaxResponse add(HttpServletRequest request, HttpServletResponse response, DTOECardChannelInfo dto) {
		String channelCode = ChannelCodeUtil.getChannelCode();
		dto.setChannelCode(channelCode);
		dto.setChannelName(channelCode);
		dto.setCreateTime(DateUtil.dateTimeToString(new Date()));
		return save(request, response, dto);
	}

	@RequestMapping("/save")
	@ResponseBody
	public BaseAjaxResponse save(HttpServletRequest request, HttpServletResponse response, DTOECardChannelInfo dto) {
		BaseAjaxResponse res = new BaseAjaxResponse();
		try {
			dto.setUpdateTime(DateUtil.dateTimeToString(new Date()));
			this.eCardChannelInfoService.saveOrUpdate(dto);
			res.setResult(BaseAjaxResponse.SUCCESS);
		} catch (Exception e) {
			res.setErrorMessage(e.getMessage());
			res.setResult(BaseAjaxResponse.FAIL);
		}
		return res;
	}

	@RequestMapping("/show/{id}")
	@ResponseBody
	public DTOECardChannelInfo showCouponType(HttpServletRequest request, HttpServletResponse response,
			@PathVariable("id") String id) {
		return this.eCardChannelInfoService.findById(id);
	}

	@RequestMapping(value = "/importChannels")
	@ResponseBody
	public BaseAjaxResponse importChannels(HttpServletRequest request, HttpServletResponse response) {
		BaseAjaxResponse res = new BaseAjaxResponse();
		int result = 0;
		try {
			MultipartRequest multipartRequest = (MultipartRequest) request;
			MultipartFile file = multipartRequest.getFile("formFile");
			ExcelReader reader = new ExcelReader(file.getInputStream(), file.getOriginalFilename());
			List<String[]> datas = reader.getAllDataByIsReadFirstColumn(0, true);
			String[] arr = null;
			List<ECardChannelInfo> list = new ArrayList<ECardChannelInfo>();
			String path = request.getRealPath("/")+"qrcodes";
			System.out.println("path:"+path);
			for (int i = 1; i <= datas.size() - 1; i++) {
				arr = datas.get(i);
				String channelId = CommonUtil.trimSpecial(arr[0]);
				String wxUrl = CommonUtil.trimSpecial(arr[1]);
				QRCodeUtil.encode(wxUrl, null, path, channelId, true);//生成二维码
			}
			result = 1;
		} catch (Exception e) {
			e.printStackTrace();
			res.setResult(2);
			res.setErrorMessage("错误：" + e.getMessage());
			return res;
		}
		if (result > 0) {
			res.setResult(1);
			res.setErrorMessage("导入成功！");
		} else {
			res.setResult(2);
			res.setErrorMessage("导入失败！");
		}
		return res;
	}

	@RequestMapping(value = "/getWechatQrcodeUrl/{channelCode}")
	@ResponseBody
	public String getWechatQrcodeUrl(@PathVariable("channelCode") String channelCode) {
		JSONObject result = new JSONObject();
		String wxUrl = createWechatQrcodeUrl(channelCode);
		result.put("wxUrl", wxUrl);
		return result.toJSONString();
	}

	private String createWechatQrcodeUrl(String channelCode) {
		//获取token
		DTOResult dtoResult = postConnServer.getWechatAccessToken(wechatAppId);
		if(dtoResult == null) return null;
		String resultData = dtoResult.getResultData();
		GetWXSignFromServer from = JSON.parseObject(resultData,GetWXSignFromServer.class);
		String accessToken = null;
		if(null != from){
			if(StringUtil.isNotEmpty(from.getAccessToken()) && StringUtil.isNotEmpty(from.getJsTicket())){
				System.out.println("获取微信Sign:" + from.toString());
				accessToken = from.getAccessToken();
			}
		}
		String url = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token="+accessToken;
		String paramStr = "{\"action_name\": \"QR_LIMIT_STR_SCENE\", \"action_info\": {\"scene\": {\"scene_str\": \""
				+ channelCode + "\"}\"}\"}";
		String sendPost = HttpRequest.sendPost(url, paramStr);
		JSONObject result = JSON.parseObject(sendPost);
		String wxUrl = result.getString("url");
		return wxUrl;
	}

	/**
	 * 批量导出渠道物料 @Title: getWechatQrcodeUrl @Description: @param
	 * count @return @throws
	 */
	@RequestMapping(value = "/batchCreateChannel/{count}")
	@ResponseBody
	public String batchCreateChannel(ModelMap model,HttpServletRequest request,HttpServletResponse response,@PathVariable("count") int count) {
		try {
			List<ECardChannelInfo> list = new ArrayList<ECardChannelInfo>();
			String path = request.getServletPath();
			for (int i = 0; i < count; i++) {
				DTOECardChannelInfo dto = new DTOECardChannelInfo();
				String channelCode = ChannelCodeUtil.getChannelCode();
				dto.setChannelCode(channelCode);
				dto.setChannelName(channelCode);
				dto.setCreateTime(DateUtil.dateTimeToString(new Date()));
				dto.setUpdateTime(DateUtil.dateTimeToString(new Date()));
				String wxUrl = createWechatQrcodeUrl(channelCode);
				dto.setQrcodeStr(wxUrl);
				ECardChannelInfo vo = this.eCardChannelInfoService.saveOrUpdate(dto);
				list.add(vo);
			}
			// 导出excel
			String exportResult = exportData(model,request, response, list);
			return exportResult;
		}catch(Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	private String exportData(ModelMap model,HttpServletRequest request, HttpServletResponse response,
			List<ECardChannelInfo> list) {

		try {
			String addName = DateUtil.dateTimeToString2(new Date()) + "_" + MathUtil.getCharAndNumr(5);
			String excelName = "channels_" + addName;
			response.setContentType("application/vnd.ms-excel;charset=GBK");
			response.setHeader("Content-Disposition", "attachment; filename=" + excelName + ".xls");
			WritableWorkbook wwb = Workbook.createWorkbook(response.getOutputStream());

			try {
				String title = "渠道物料导出";

				String[] titles = new String[] { "渠道号", "二维码链接" };

				WritableFont titleFont = new WritableFont(WritableFont.TIMES, 11, WritableFont.BOLD, false);
				WritableCellFormat format = new WritableCellFormat(titleFont);
				format.setBorder(Border.ALL, BorderLineStyle.THIN, Colour.BLACK);
				format.setBackground(Colour.GRAY_25);
				WritableFont vFont = new WritableFont(WritableFont.TIMES, 11, WritableFont.NO_BOLD, false);
				WritableCellFormat vFormat = new WritableCellFormat(vFont);
				vFormat.setBorder(Border.ALL, BorderLineStyle.THIN, Colour.BLACK);
				jxl.write.WritableSheet ws = wwb.createSheet(title, 0);
				CellView cellView = new CellView();
				cellView.setAutosize(true); // 设置自动大小

				// 共有几个字段；
				int rowIndex = 0;
				for (int i = 0; i < titles.length; i++) {
					Label labelC = new Label(i, rowIndex, titles[i], format);
					ws.addCell(labelC);
				}

				if (list != null) {
					for (int n = 0; n < list.size(); n++) {
						rowIndex++;
						ECardChannelInfo dto = list.get(n);

						String[] values = new String[] { dto.getId(), dto.getQrcodeStr()};

						for (int i = 0; i < values.length; i++) {
							Label labelC = new Label(i, rowIndex, values[i], vFormat);
							ws.setColumnView(i, cellView);// 自动列宽
							ws.addCell(labelC);
						}
					}
				}

				wwb.write();
			} finally {
				wwb.close();
			}

		} catch (Exception e) {
			e.printStackTrace();
			model.put("e", e);
			model.put("errMsg", e.getMessage());
			return WebUtil.BACKEND_ERR_PAGE;
		}
		return null;
	}
	
	@RequestMapping(value = "/checkAutoReturn")
	public void checkAutoReturn() {
		checkSendRecordTaskService.checkSendRecord();
	}
	
	@RequestMapping("/officialChannel")
	public String search(ModelMap modelMap,HttpServletRequest request,HttpServletResponse response){
		return "/official_channel";
	}
	
}
